import axios from 'axios'
// 获取当前日期范围
export function getNowDate() {
  let now = new Date()
  let year = now.getFullYear()
  let month = now.getMonth()
  let date = now.getDate()
  month = month + 1
  month = month.toString().padStart(2, '0')
  date = date.toString().padStart(2, '0')
  let defaultDate = `${year}-${month}-${date}`
  return defaultDate
}
// 获取当前日期后的一年
export function getPassYear () {
  let nowDate = new Date()
  let date = new Date(nowDate)
  date.setDate(date.getDate() + 365)
  let year = date.getFullYear()
  let month = date.getMonth() + 1
  let strDate = date.getDate()
  if (month >= 1 && month <= 9) {
    month = '0' + month
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = '0' + strDate
  }
  let formatDate = `${year}-${month}-${strDate}`
  return formatDate
}

export function isDecimal(num) {
  num = `${num}`
  let patt = /^-?\d+\.?\d{0,2}$/;
  let trimStr = num.replace(/[\t\r\f\n\s]*/g, '')
  let boo = patt.test(trimStr);
  //增强校验
  if (boo) {
    //校验如01
    if (num.substr(0, 1) == '0' && num.indexOf('.') == -1 && num.length > 1) {
      return false;
    }
    //校验如"0."、"10."
    if (num.substr(num.length-1,1) == '.') {
      return false;
    }
  }
  return boo;
}

export function getTimeState() {
  // 获取当前时间
  let timeNow = new Date();
  // 获取当前小时
  let hours = timeNow.getHours();
  // 设置默认文字
  let state = ``;
  // 判断当前时间段
  if (hours >= 0 && hours <= 10) {
    state = `早上好`;
  } else if (hours > 10 && hours <= 14) {
    state = `中午好`;
  } else if (hours > 14 && hours <= 18) {
    state = `下午好`;
  } else if (hours > 18 && hours <= 24) {
    state = `晚上好`;
  }
  return state;
}

export function isPhoneNum(str) {
  return /^1[3|4|5|6|7|8|9][0-9]\d{8}$/.test(str)
}

export function px2rem(px){
  if(/%/ig.test(px)){ // 有百分号%，特殊处理，表述pc是一个有百分号的数，比如：90%
    return px
  }else{
    // return (parseFloat(px) / 192) + 'rem'
    return px
  }
}
export const LLKeyBord = (param, options, successFn = () => {}, failFn = () => {}) => {
  let {click_objId, Input_texId, parent_objId, placeholderId} = param
  return new showKeyBord({
    'png': '//mpay-static.oss-cn-hangzhou.aliyuncs.com/html/lib/state-secret/img', // 图片路径，用这个就行了，也可以下载到本地
    'click_objId': click_objId, // 触发显示键盘的Dom节点Id
    'regExp1': '^[a-zA-Z0-9]+$', // 输入过程限制的正则，不匹配正则的字符不让输入
    'regExp2': '^[\\S\\s]{6,12}$', // 输入完成后的正则，与getValid()对应，判断输入值是否匹配该正则
    'Input_texId': Input_texId, // 接收内容的Dom节点Id
    'parent_objId': parent_objId, // 将键盘插入到何处的Dom节点Id
    'placeholderId': placeholderId, // span标签的id，该span用于模拟Input_texId的placeholder
    'len': '12', // 表示最大允许输入多少个字符[可以不传递]
    'keyBordLeft': '',
    'keyBordTop': '',
    'chaosMode': 0, // 混乱模式,0:无混乱;1:打开时乱一次;2:每输入一个字符乱一次,默认值0
    'clickStatus': 0, // 按键状态,0:鼠标划过、悬浮时按键无变化;1:鼠标划过、悬浮时按键的颜色变化,默认值0
    'titlefont': '安全支付输入',
    'backfont': '退 格',
    'capsfont': '切换大/小写',
    'surefont': '确定',
    'isen': false,
    'callBack': (res) => {
      successFn()
    }, // 密码校验成功回调
    'errorCallBack': (err) => {
      failFn()
    }, // 密码校验失败回调
    'rsaPublicKey': options.rsa_public_content, // RSA加密必须参数，国密加密可不要
    'sm2KeyHex': options.sm2_key_hex, // 国密加密必须参数，RSA加密可不要
    'license': options.license, // 必须参数
  })
}

//将base64转换为blob
export const dataURLtoBlob = (dataurl) => {
  const arr = dataurl.split(',');
  const  mime = arr[0].match(/:(.*?);/)[1];
  const  bstr = atob(arr[1]);
  let  n = bstr.length;
  const  u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], {type: mime});
}


//将blob转换为file
export const blobToFile = (theBlob, fileName) => {
  const file = new File([theBlob], fileName)
  return file;
}

export const getImageFromUrl = (url) => {
  return axios({
    url,
    method: 'get',
    responseType: 'blob' // 指定响应数据的类型为 blob（二进制数据）
  }).then(response => {
    const fileReader = new FileReader();
    fileReader.readAsDataURL(response.data); // 读取二进制数据并转换为 Base64 格式
    return new Promise(resolve => {
      fileReader.onload = () => {
        const base64Data = fileReader.result;
        resolve(base64Data);
      };
    });
  });
}

export const trimAllStr = (ele) => {
  if(typeof ele === 'string'){
    return ele.split(/[\t\r\f\n\s]*/g).join('');
  }else{
      console.error(`${typeof ele} is not the expected type, but the string type is expected`)
  }
}